import*as e from"../../core/sdk/sdk.js";import*as t from"../../core/common/common.js";import*as r from"../../core/i18n/i18n.js";import*as a from"../../core/platform/platform.js";import*as n from"../../core/root/root.js";import*as i from"../trace/trace.js";const s={threadS:"Thread {PH1}"},o=r.i18n.registerUIStrings("models/timeline_model/TimelineJSProfile.ts",s),l=r.i18n.getLocalizedString.bind(void 0,o);class d{static generateConstructedEventsFromCpuProfileDataModel(t,r){const a=t.samples||[],n=t.timestamps,i=[],s=new Map;let o=t.root,l=[];for(let d=0;d<a.length;++d){const c=t.nodeByIndex(d);if(!c){console.error(`Node with unknown id ${a[d]} at index ${d}`);continue}let h;if(c===t.gcNode)h=o===t.gcNode?l:[c,...l];else if(h=s.get(c),!h){h=new Array(c.depth+1),s.set(c,h);let e=c;for(let t=0;e.parent;e=e.parent)h[t++]=e}const m=c===t.idleNode?g.JSIdleSample:c===t.programNode||c===t.gcNode?g.JSSystemSample:g.JSSample,u=new e.TracingModel.ConstructedEvent(e.TracingModel.DevToolsTimelineEventCategory,m,"I",n[d],r);u.args.data={stackTrace:h},i.push(u),o=c,l=h}return i}static isJSSampleEvent(e){return e.name===g.JSSample||e.name===g.JSSystemSample||e.name===g.JSIdleSample}static generateJSFrameEvents(t,r){const a=[],n=[],i=[];let s=0,o=!1;const{showAllEvents:l,showRuntimeCallStats:c,showNativeFunctions:h}=r;function m(e,t){if(i.length){const r=i.at(-1);r&&e<r&&(console.error(`Child stack is shallower (${e}) than the parent stack (${r}) at ${t}`),e=r)}n.length<e&&(console.error(`Trying to truncate higher than the current stack size at ${t}`),e=n.length);for(let e=0;e<n.length;++e)n[e].setEndTime(t);n.length=e}function u(t){const r=d.isJSSampleEvent(t)?t.args.data.stackTrace.slice().reverse():n.map((e=>e.args.data));!function(e){if(l)return;let t=null,r=0;for(let n=0;n<e.length;++n){const i=e[n],s=i.url,o=s&&s.startsWith("native ");if(!h&&o)continue;const l=d.isNativeRuntimeFrame(i);if(l&&(a=i.functionName,!c||!Boolean(d.nativeGroup(a))))continue;const m=l?d.nativeGroup(i.functionName):null;t&&t===m||(t=m,e[r++]=i)}var a;e.length=r}(r);const s=t.endTime||t.startTime,o=Math.min(r.length,n.length);let u;for(u=i.at(-1)||0;u<o;++u){const e=r[u],t=n[u].args.data;if(T=t,(p=e).scriptId!==T.scriptId||p.functionName!==T.functionName||p.lineNumber!==T.lineNumber)break;n[u].setEndTime(Math.max(n[u].endTime,s))}var p,T;for(m(u,t.startTime);u<r.length;++u){const i=r[u];let o=g.JSFrame;switch(t.name){case g.JSIdleSample:o=g.JSIdleFrame;break;case g.JSSystemSample:o=g.JSSystemFrame}const l=new e.TracingModel.ConstructedEvent(e.TracingModel.DevToolsTimelineEventCategory,o,"X",t.startTime,t.thread);l.ordinal=t.ordinal,l.addArgs({data:i}),l.setEndTime(s),n.push(l),a.push(l)}}const T=t.find(e.TracingModel.TracingModel.isTopLevelEvent),v=T?T.startTime:0;return p.forEachEvent(t,(function(t){e.TracingModel.eventIsFromNewEngine(t)||(o&&(m(i.pop(),t.startTime),o=!1),t.ordinal=++s,u(t),i.push(n.length))}),(function(t){e.TracingModel.eventIsFromNewEngine(t)||m(i.pop(),t.endTime)}),(function(t,r){if(!e.TracingModel.eventIsFromNewEngine(t)&&!e.TracingModel.eventIsFromNewEngine(r))if(t.ordinal=++s,r&&function(e){switch(e.name){case g.RunMicrotasks:case g.FunctionCall:case g.EvaluateScript:case g.EvaluateModule:case g.EventDispatch:case g.V8Execute:return!0}return!(!e.name.startsWith("v8")&&!e.name.startsWith("V8"))}(r)||o)u(t);else if(d.isJSSampleEvent(t)&&t.args?.data?.stackTrace?.length&&0===n.length){o=!0;const e=n.length;u(t),i.push(e)}}),v),a}static isNativeRuntimeFrame(e){return"native V8Runtime"===e.url}static nativeGroup(e){return e.startsWith("Parse")?d.NativeGroups.Parse:e.startsWith("Compile")||e.startsWith("Recompile")?d.NativeGroups.Compile:null}static createFakeTraceFromCpuProfile(t,r,a,n){const i=[];return a&&o("TracingStartedInPage",{data:{sessionId:"1"}},0,0,"M"),n||(n=l(s.threadS,{PH1:r})),o(e.TracingModel.MetadataEvent.ThreadName,{name:n},0,0,"M","__metadata"),t?(o(g.JSRoot,{},t.startTime,t.endTime-t.startTime,"X","toplevel"),o("CpuProfile",{data:{cpuProfile:t}},t.endTime,0,"I"),i):i;function o(e,t,a,n,s,o){const l={cat:o||"disabled-by-default-devtools.timeline",name:e,ph:s||"X",pid:1,tid:r,ts:a,args:t};return n&&(l.dur=n),i.push(l),l}}}!function(e){let t;!function(e){e.Compile="Compile",e.Parse="Parse"}(t=e.NativeGroups||(e.NativeGroups={}))}(d||(d={}));var c=Object.freeze({__proto__:null,get TimelineJSProfileProcessor(){return d}});const h={threadS:"Thread {PH1}",workerS:"`Worker` — {PH1}",dedicatedWorker:"Dedicated `Worker`",workerSS:"`Worker`: {PH1} — {PH2}",bidderWorkletS:"Bidder Worklet — {PH1}",sellerWorkletS:"Seller Worklet — {PH1}",unknownWorkletS:"Auction Worklet — {PH1}",bidderWorklet:"Bidder Worklet",sellerWorklet:"Seller Worklet",unknownWorklet:"Auction Worklet",workletService:"Auction Worklet Service",workletServiceS:"Auction Worklet Service — {PH1}"},m=r.i18n.registerUIStrings("models/timeline_model/TimelineModel.ts",h),u=r.i18n.getLocalizedString.bind(void 0,m);class p{isGenericTraceInternal;tracksInternal;namedTracks;inspectedTargetEventsInternal;timeMarkerEventsInternal;sessionId;mainFrameNodeId;pageFrames;auctionWorklets;cpuProfilesInternal;workerIdByThread;requestsFromBrowser;mainFrame;minimumRecordTimeInternal;maximumRecordTimeInternal;totalBlockingTimeInternal;estimatedTotalBlockingTime;asyncEventTracker;invalidationTracker;layoutInvalidate;lastScheduleStyleRecalculation;paintImageEventByPixelRefId;lastPaintForLayer;lastRecalculateStylesEvent;currentScriptEvent;eventStack;browserFrameTracking;persistentIds;legacyCurrentPage;currentTaskLayoutAndRecalcEvents;tracingModelInternal;mainFrameLayerTreeId;#e=!1;constructor(){this.minimumRecordTimeInternal=0,this.maximumRecordTimeInternal=0,this.totalBlockingTimeInternal=0,this.estimatedTotalBlockingTime=0,this.reset(),this.resetProcessingState(),this.currentTaskLayoutAndRecalcEvents=[],this.tracingModelInternal=null}static forEachEvent(t,r,a,n,s,o,l,d=!0){s=s||0,o=o||1/0;const c=[];for(let h=p.topLevelEventEndingAfter(t,s);h<t.length;++h){const m=t[h],{endTime:u,startTime:p,duration:g}=e.TracingModel.timesForEventInMilliseconds(m),T=e.TracingModel.phaseForEvent(m);if((u||p)<s)continue;if(p>=o)break;if(d&&i.Types.TraceEvents.isAsyncPhase(T)||i.Types.TraceEvents.isFlowPhase(T))continue;let v=c[c.length-1],f=v&&e.TracingModel.timesForEventInMilliseconds(v).endTime;for(;v&&void 0!==f&&f<=p;)c.pop(),a(v),v=c[c.length-1],f=v&&e.TracingModel.timesForEventInMilliseconds(v).endTime;l&&!l(m)||(g?(r(m),c.push(m)):n&&n(m,c[c.length-1]||null))}for(;c.length;){const e=c.pop();e&&a(e)}}static topLevelEventEndingAfter(t,r){let n=a.ArrayUtilities.upperBound(t,r,((t,r)=>t-e.TracingModel.timesForEventInMilliseconds(r).startTime))-1;for(;n>0&&!e.TracingModel.TracingModel.isTopLevelEvent(t[n]);)n--;return Math.max(n,0)}mainFrameID(){return this.mainFrame.frameId}isMarkerEvent(e){switch(e.name){case g.TimeStamp:return!0;case g.MarkFirstPaint:case g.MarkFCP:return Boolean(this.mainFrame)&&e.args.frame===this.mainFrame.frameId&&Boolean(e.args.data);case g.MarkDOMContent:case g.MarkLoad:case g.MarkLCPCandidate:case g.MarkLCPInvalidate:return Boolean(e.args.data.isOutermostMainFrame??e.args.data.isMainFrame);default:return!1}}isInteractiveTimeEvent(e){return e.name===g.InteractiveTime}isLayoutShiftEvent(e){return e.name===g.LayoutShift}isParseHTMLEvent(e){return e.name===g.ParseHTML}static isJsFrameEvent(e){return e.name===g.JSFrame||e.name===g.JSIdleFrame||e.name===g.JSSystemFrame}static globalEventId(e,t){const r=e.args.data||e.args.beginData,a=r&&r[t];return a?`${e.thread.process().id()}.${a}`:""}static eventFrameId(e){const t=e.args.data||e.args.beginData;return t&&t.frame||null}cpuProfiles(){return this.cpuProfilesInternal}totalBlockingTime(){return-1===this.totalBlockingTimeInternal?{time:this.estimatedTotalBlockingTime,estimated:!0}:{time:this.totalBlockingTimeInternal,estimated:!1}}targetByEvent(t){let r;if(t instanceof e.TracingModel.Event)r=t.thread;else{const e=this.tracingModelInternal?.getProcessById(t.pid);r=e?.threadById(t.tid)}if(!r)return null;const a=this.workerIdByThread.get(r),n=e.TargetManager.TargetManager.instance().primaryPageTarget();return a?e.TargetManager.TargetManager.instance().targetById(a):n}navStartTimes(){return this.tracingModelInternal?this.tracingModelInternal.navStartTimes():new Map}isFreshRecording(){return this.#e}setEvents(t,r=!1){this.#e=r,this.reset(),this.resetProcessingState(),this.tracingModelInternal=t,this.minimumRecordTimeInternal=t.minimumRecordTime(),this.maximumRecordTimeInternal=t.maximumRecordTime();const a=[];for(const e of t.sortedProcesses())if("Renderer"===e.name())for(const t of e.sortedThreads()){const e=t.removeEventsByName(g.LayoutShift);a.push(...e)}if(this.processSyncBrowserEvents(t),this.browserFrameTracking)this.processThreadsForBrowserFrames(t);else{const e=this.processMetadataEvents(t);this.isGenericTraceInternal=!e,e?this.processMetadataAndThreads(t,e):this.processGenericTrace(t)}this.inspectedTargetEventsInternal.sort(e.TracingModel.Event.compareStartTime),this.processAsyncBrowserEvents(t),this.resetProcessingState()}processGenericTrace(t){let r=e.TracingModel.TracingModel.browserMainThread(t);!r&&t.sortedProcesses().length&&(r=t.sortedProcesses()[0].sortedThreads()[0]);for(const e of t.sortedProcesses())for(const a of e.sortedThreads())this.processThreadEvents(t,a,a===r,!1,!0,0,null)}processMetadataAndThreads(e,t){let r=0;for(let n=0,i=t.page.length;n<i;n++){const s=t.page[n],o=s.thread.process(),l=n+1<i?t.page[n+1].startTime:1/0;if(r!==l){this.legacyCurrentPage=s.args.data&&s.args.data.page;for(const r of o.sortedThreads()){let n=null;if(r.name()===p.WorkerThreadName||r.name()===p.WorkerThreadNameLegacy){const e=t.workers.find((e=>{if(e.args.data.workerThreadId!==r.id())return!1;if(e.args.data.sessionId===this.sessionId)return!0;const t=p.eventFrameId(e);return!!t&&Boolean(this.pageFrames.get(t))}));if(!e)continue;const i=e.args.data.workerId;i&&this.workerIdByThread.set(r,i),n=e.args.data.url||a.DevToolsPath.EmptyUrlString}this.processThreadEvents(e,r,r===s.thread,Boolean(n),!0,0,n)}r=l}}}processThreadsForBrowserFrames(e){const t=new Map;for(const e of this.pageFrames.values())for(let r=0;r<e.processes.length;r++){const a=e.processes[r].processId;let n=t.get(a);n||(n=[],t.set(a,n));const i=r===e.processes.length-1?e.deletedTime||1/0:e.processes[r+1].time;n.push({from:e.processes[r].time,to:i,main:!e.parent,url:e.processes[r].url,workletType:0})}for(const e of this.auctionWorklets.values()){const r=e.processId;let n=t.get(r);n||(n=[],t.set(r,n)),n.push({from:e.startTime,to:e.endTime,main:!1,workletType:e.workletType,url:e.host?"https://"+e.host:a.DevToolsPath.EmptyUrlString})}const r=e.devToolsMetadataEvents();for(const n of e.sortedProcesses()){const i=t.get(n.id());if(!i)continue;i.sort(((e,t)=>e.from-t.from||e.to-t.to));let s=null,o=null,l=!1,d=!0,c=!1,h=0;for(const e of i)e.main&&(l=!0),e.url&&(e.main&&(o=e.url),s=e.url),0===e.workletType?d=!1:(!1===c?c=e.url:c!==e.url&&(c=!0),0===h?h=e.workletType:h!==e.workletType&&(h=3));for(const t of n.sortedThreads())if(t.name()===p.RendererMainThreadName)this.processThreadEvents(e,t,!0,!1,l,0,l?o:s);else if(t.name()===p.WorkerThreadName||t.name()===p.WorkerThreadNameLegacy){const i=r.find((e=>{if(e.name!==p.DevToolsMetadataEvent.TracingSessionIdForWorker)return!1;if(e.thread.process()!==n)return!1;if(e.args.data.workerThreadId!==t.id())return!1;const r=p.eventFrameId(e);return!!r&&Boolean(this.pageFrames.get(r))}));if(!i)continue;this.workerIdByThread.set(t,i.args.data.workerId||""),this.processThreadEvents(e,t,!1,!0,!1,0,i.args.data.url||a.DevToolsPath.EmptyUrlString)}else{let r=null,a=0;if(t.name()===p.AuctionWorkletThreadName||t.name().endsWith(p.UtilityMainThreadNameSuffix))"boolean"!=typeof c&&(r=c),a=h;else if(d)continue;this.processThreadEvents(e,t,!1,!1,!1,a,r)}}}processMetadataEvents(r){const a=r.devToolsMetadataEvents(),n=[],i=[];for(const e of a)if(e.name===p.DevToolsMetadataEvent.TracingStartedInPage){n.push(e),e.args.data&&e.args.data.persistentIds&&(this.persistentIds=!0);(e.args.data&&e.args.data.frames||[]).forEach((t=>this.addPageFrame(e,t))),this.mainFrame=this.rootFrames()[0]}else e.name===p.DevToolsMetadataEvent.TracingSessionIdForWorker?i.push(e):e.name===p.DevToolsMetadataEvent.TracingStartedInBrowser&&(console.assert(!this.mainFrameNodeId,"Multiple sessions in trace"),this.mainFrameNodeId=e.args.frameTreeNodeId);if(!n.length)return null;const s=n[0].args.sessionId||n[0].args.data.sessionId;this.sessionId=s;const o=new Set;const l={page:n.filter((function(e){let t=e.args;t.data&&(t=t.data);const r=t.sessionId;return r===s||(o.add(r),!1)})).sort(e.TracingModel.Event.compareStartTime),workers:i.sort(e.TracingModel.Event.compareStartTime)};return o.size&&t.Console.Console.instance().error("Timeline recording was started in more than one page simultaneously. Session id mismatch: "+this.sessionId+" and "+[...o]+"."),l}processSyncBrowserEvents(t){const r=e.TracingModel.TracingModel.browserMainThread(t);r&&r.events().forEach(this.processBrowserEvent,this)}processAsyncBrowserEvents(t){const r=e.TracingModel.TracingModel.browserMainThread(t);r&&this.processAsyncEvents(r)}resetProcessingState(){this.asyncEventTracker=new F,this.invalidationTracker=new k,this.layoutInvalidate={},this.lastScheduleStyleRecalculation={},this.paintImageEventByPixelRefId={},this.lastPaintForLayer={},this.lastRecalculateStylesEvent=null,this.currentScriptEvent=null,this.eventStack=[],this.browserFrameTracking=!1,this.persistentIds=!1,this.legacyCurrentPage=null}extractCpuProfileDataModel(r,a){const n=a.events();let i,s=null,o=n.at(-1);if(o&&o.name===g.CpuProfile){const e=o.args.data;i=e&&e.cpuProfile,s=this.targetByEvent(o)}if(!i){if(o=n.find((e=>e.name===g.Profile)),!o)return null;s=this.targetByEvent(o);const e=r.profileGroup(o);if(!e)return t.Console.Console.instance().error("Invalid CPU profile format."),null;i={startTime:1e3*o.startTime,endTime:0,nodes:[],samples:[],timeDeltas:[],lines:[]};for(const r of e.children){const e=r.args.data;"startTime"in e&&(i.startTime=1e3*r.startTime),"endTime"in e&&(i.endTime=1e3*r.startTime);const a=e.cpuProfile||{},n=a.samples||[],s=e.lines||Array(n.length).fill(0);if(i.nodes.push(...a.nodes||[]),i.lines.push(...s),i.samples&&i.samples.push(...n),i.timeDeltas&&i.timeDeltas.push(...e.timeDeltas||[]),i.samples&&i.timeDeltas&&i.samples.length!==i.timeDeltas.length)return t.Console.Console.instance().error("Failed to parse CPU profile."),null}if(!i.endTime&&i.timeDeltas){const e=i.timeDeltas;i.endTime=e.reduce(((e,t)=>e+t),i.startTime)}}try{const t=i,r=new e.CPUProfileDataModel.CPUProfileDataModel(t,s);return this.cpuProfilesInternal.push(r),r}catch(e){t.Console.Console.instance().error("Failed to parse CPU profile.")}return null}injectJSFrameEvents(r,i){const s=this.extractCpuProfileDataModel(r,i);let o=i.events();const l=s?d.generateConstructedEventsFromCpuProfileDataModel(s,i):null;if(l&&l.length&&(o=a.ArrayUtilities.mergeOrdered(o,l,e.TracingModel.Event.orderedCompareStartTime)),l||o.some((e=>e.name===g.JSSample||e.name===g.JSSystemSample||e.name===g.JSIdleSample))){const r=d.generateJSFrameEvents(o,{showAllEvents:n.Runtime.experiments.isEnabled("timelineShowAllEvents"),showRuntimeCallStats:n.Runtime.experiments.isEnabled("timelineV8RuntimeCallStats"),showNativeFunctions:t.Settings.Settings.instance().moduleSetting("showNativeFunctionsInJSProfile").get()});r&&r.length&&(o=a.ArrayUtilities.mergeOrdered(r,o,e.TracingModel.Event.orderedCompareStartTime))}return o}static nameAuctionWorklet(e,t){switch(e){case 1:return t?u(h.bidderWorkletS,{PH1:t}):u(h.bidderWorklet);case 2:return t?u(h.sellerWorkletS,{PH1:t}):u(h.sellerWorklet);default:return t?u(h.unknownWorkletS,{PH1:t}):u(h.unknownWorklet)}}processThreadEvents(e,t,r,n,s,o,l){const d=new v;d.name=t.name()||u(h.threadS,{PH1:t.id()}),d.type=T.Other,d.thread=t,r?(d.type=T.MainThread,d.url=l||a.DevToolsPath.EmptyUrlString,d.forMainFrame=s):n?(d.type=T.Worker,d.url=l||a.DevToolsPath.EmptyUrlString,d.name=d.url?u(h.workerS,{PH1:d.url}):u(h.dedicatedWorker)):t.name().startsWith("CompositorTileWorker")?d.type=T.Raster:t.name()===p.AuctionWorkletThreadName?(d.url=l||a.DevToolsPath.EmptyUrlString,d.name=p.nameAuctionWorklet(o,l)):0!==o&&t.name().endsWith(p.UtilityMainThreadNameSuffix)&&(d.url=l||a.DevToolsPath.EmptyUrlString,d.name=l?u(h.workletServiceS,{PH1:l}):u(h.workletService)),this.tracksInternal.push(d);const c=this.injectJSFrameEvents(e,t);this.eventStack=[];const m=this.eventStack;if(n){const e=c.find((e=>e.name===g.Profile));if(e){const t=this.targetByEvent(e);t&&(d.name=u(h.workerSS,{PH1:t.name(),PH2:d.url}))}}for(let e=0;e<c.length;e++){const t=c[e];this.isInteractiveTimeEvent(t)&&-1===this.totalBlockingTimeInternal&&(this.totalBlockingTimeInternal=t.args.args.total_blocking_time_ms);const a=t.name===g.Task&&t.duration&&t.duration>50;r&&a&&t.duration&&(this.estimatedTotalBlockingTime+=t.duration-50);let n=m[m.length-1];for(;n&&void 0!==n.endTime&&n.endTime<=t.startTime;)m.pop(),n=m[m.length-1];if(this.processEvent(t)){if(!i.Types.TraceEvents.isAsyncPhase(t.phase)&&t.duration){if(m.length){const e=m[m.length-1];e&&(e.selfTime-=t.duration,e.selfTime<0&&this.fixNegativeDuration(e,t))}t.selfTime=t.duration,m.length||d.tasks.push(t),m.push(t)}this.isMarkerEvent(t)&&this.timeMarkerEventsInternal.push(t),d.events.push(t),this.inspectedTargetEventsInternal.push(t)}}this.processAsyncEvents(t)}fixNegativeDuration(e,t){e.selfTime<-.001&&console.error(`Children are longer than parent at ${e.startTime} (${(t.startTime-this.minimumRecordTime()).toFixed(3)} by ${(-e.selfTime).toFixed(3)}`),e.selfTime=0}processAsyncEvents(t){const r=t.asyncEvents(),n=new Map;for(let e=0;e<r.length;++e){const t=r[e];t.name!==g.Animation||(i=T.Animation,n.has(i)||n.set(i,[]),n.get(i)).push(t)}var i;for(const[r,i]of n){const n=this.ensureNamedTrack(r);n.thread=t,n.asyncEvents=a.ArrayUtilities.mergeOrdered(n.asyncEvents,i,e.TracingModel.Event.compareStartTime)}}processEvent(e){const t=this.eventStack;if(!t.length){if(this.currentTaskLayoutAndRecalcEvents&&this.currentTaskLayoutAndRecalcEvents.length){const e=this.currentTaskLayoutAndRecalcEvents.reduce(((e,t)=>void 0===t.duration?e:e+t.duration),0);if(e>p.Thresholds.ForcedLayout)for(const e of this.currentTaskLayoutAndRecalcEvents){R.forEvent(e).warning=e.name===g.Layout?p.WarningType.ForcedLayout:p.WarningType.ForcedStyle}}this.currentTaskLayoutAndRecalcEvents=[]}this.currentScriptEvent&&void 0!==this.currentScriptEvent.endTime&&e.startTime>this.currentScriptEvent.endTime&&(this.currentScriptEvent=null);const r=e.args.data||e.args.beginData||{},a=R.forEvent(e);r.stackTrace&&(a.stackTrace=r.stackTrace.map((t=>{if(e.name!==g.JSSample&&e.name!==g.JSSystemSample&&e.name!==g.JSIdleSample){const e={...t};return--e.lineNumber,--e.columnNumber,e}return t})));let n=p.eventFrameId(e);const i=t[t.length-1];switch(!n&&i&&(n=R.forEvent(i).frameId),a.frameId=n||this.mainFrame&&this.mainFrame.frameId||"",this.asyncEventTracker.processEvent(e),e.name){case g.ResourceSendRequest:case g.WebSocketCreate:a.setInitiator(t[t.length-1]||null),a.url=r.url;break;case g.ScheduleStyleRecalculation:this.lastScheduleStyleRecalculation[r.frame]=e;break;case g.UpdateLayoutTree:case g.RecalculateStyles:this.invalidationTracker.didRecalcStyle(e),e.args.beginData&&a.setInitiator(this.lastScheduleStyleRecalculation[e.args.beginData.frame]),this.lastRecalculateStylesEvent=e,this.currentScriptEvent&&this.currentTaskLayoutAndRecalcEvents.push(e);break;case g.ScheduleStyleInvalidationTracking:case g.StyleRecalcInvalidationTracking:case g.StyleInvalidatorInvalidationTracking:case g.LayoutInvalidationTracking:this.invalidationTracker.addInvalidation(new S(e,a));break;case g.InvalidateLayout:{let t=e;const a=r.frame;!this.layoutInvalidate[a]&&this.lastRecalculateStylesEvent&&void 0!==this.lastRecalculateStylesEvent.endTime&&this.lastRecalculateStylesEvent.endTime>e.startTime&&(t=R.forEvent(this.lastRecalculateStylesEvent).initiator()),this.layoutInvalidate[a]=t;break}case g.Layout:{this.invalidationTracker.didLayout(e);const t=e.args.beginData.frame;if(a.setInitiator(this.layoutInvalidate[t]),e.args.endData)if(e.args.endData.layoutRoots)for(let t=0;t<e.args.endData.layoutRoots.length;++t)a.backendNodeIds.push(e.args.endData.layoutRoots[t].nodeId);else a.backendNodeIds.push(e.args.endData.rootNode);this.layoutInvalidate[t]=null,this.currentScriptEvent&&this.currentTaskLayoutAndRecalcEvents.push(e);break}case g.Task:void 0!==e.duration&&e.duration>p.Thresholds.LongTask&&(a.warning=p.WarningType.LongTask);break;case g.EventDispatch:void 0!==e.duration&&e.duration>p.Thresholds.RecurringHandler&&(a.warning=p.WarningType.LongHandler);break;case g.TimerFire:case g.FireAnimationFrame:void 0!==e.duration&&e.duration>p.Thresholds.RecurringHandler&&(a.warning=p.WarningType.LongRecurringHandler);break;case g.FunctionCall:"string"==typeof r.scriptName&&(r.url=r.scriptName),"number"==typeof r.scriptLine&&(r.lineNumber=r.scriptLine);case g.EvaluateScript:case g.CompileScript:case g.CacheScript:"number"==typeof r.lineNumber&&--r.lineNumber,"number"==typeof r.columnNumber&&--r.columnNumber;case g.RunMicrotasks:this.currentScriptEvent||(this.currentScriptEvent=e);break;case g.SetLayerTreeId:{if(this.sessionId&&r.sessionId&&this.sessionId===r.sessionId){this.mainFrameLayerTreeId=r.layerTreeId;break}const t=p.eventFrameId(e),a=t?this.pageFrames.get(t):null;if(!a||a.parent)return!1;this.mainFrameLayerTreeId=r.layerTreeId;break}case g.Paint:{if(this.invalidationTracker.didPaint=!0,"nodeId"in r&&a.backendNodeIds.push(r.nodeId),!r.layerId)break;const t=r.layerId;this.lastPaintForLayer[t]=e;break}case g.DisplayItemListSnapshot:case g.PictureSnapshot:{const t=this.findAncestorEvent(g.UpdateLayer);if(!t||t.args.layerTreeId!==this.mainFrameLayerTreeId)break;const r=this.lastPaintForLayer[t.args.layerId];r&&(R.forEvent(r).picture=e);break}case g.ScrollLayer:a.backendNodeIds.push(r.nodeId);break;case g.PaintImage:a.backendNodeIds.push(r.nodeId),a.url=r.url;break;case g.DecodeImage:case g.ResizeImage:{let e=this.findAncestorEvent(g.PaintImage);if(!e){const t=this.findAncestorEvent(g.DecodeLazyPixelRef);e=t&&this.paintImageEventByPixelRefId[t.args.LazyPixelRef]}if(!e)break;const t=R.forEvent(e);a.backendNodeIds.push(t.backendNodeIds[0]),a.url=t.url;break}case g.DrawLazyPixelRef:{const t=this.findAncestorEvent(g.PaintImage);if(!t)break;this.paintImageEventByPixelRefId[e.args.LazyPixelRef]=t;const r=R.forEvent(t);a.backendNodeIds.push(r.backendNodeIds[0]),a.url=r.url;break}case g.FrameStartedLoading:if(a.frameId!==e.args.frame)return!1;break;case g.MarkLCPCandidate:a.backendNodeIds.push(r.nodeId);break;case g.MarkDOMContent:case g.MarkLoad:{const t=p.eventFrameId(e);if(!t||!this.pageFrames.has(t))return!1;break}case g.CommitLoad:{if(this.browserFrameTracking)break;const t=p.eventFrameId(e),a=Boolean(r.isOutermostMainFrame??r.isMainFrame),n=t?this.pageFrames.get(t):null;if(n)n.update(e.startTime,r);else if(this.persistentIds){if(a)return!1;if(!this.addPageFrame(e,r))return!1}else if(r.page&&r.page!==this.legacyCurrentPage)return!1;if(a&&t){const e=this.pageFrames.get(t);e&&(this.mainFrame=e)}break}case g.FireIdleCallback:void 0!==e.duration&&e.duration>r.allottedMilliseconds+p.Thresholds.IdleCallbackAddon&&(a.warning=p.WarningType.IdleDeadlineExceeded)}return!0}processBrowserEvent(t){if(t.name!==g.ResourceWillSendRequest){if(t.hasCategory(e.TracingModel.DevToolsMetadataEventCategory)&&t.args.data){const e=t.args.data;if(t.name===p.DevToolsMetadataEvent.TracingStartedInBrowser){if(!e.persistentIds)return;this.browserFrameTracking=!0,this.mainFrameNodeId=e.frameTreeNodeId;return void(e.frames||[]).forEach((e=>{const t=e.parent&&this.pageFrames.get(e.parent);if(e.parent&&!t)return;let r=this.pageFrames.get(e.frame);r||(r=new f(e),this.pageFrames.set(r.frameId,r),t?t.addChild(r):this.mainFrame=r),r.update(this.minimumRecordTimeInternal,e)}))}if(t.name===p.DevToolsMetadataEvent.FrameCommittedInBrowser&&this.browserFrameTracking){let r=this.pageFrames.get(e.frame);if(!r){const t=e.parent&&this.pageFrames.get(e.parent);if(!t)return;r=new f(e),this.pageFrames.set(r.frameId,r),t.addChild(r)}return void r.update(t.startTime,e)}if(t.name===p.DevToolsMetadataEvent.ProcessReadyInBrowser&&this.browserFrameTracking){const t=this.pageFrames.get(e.frame);return void(t&&t.processReady(e.processPseudoId,e.processId))}if(t.name===p.DevToolsMetadataEvent.FrameDeletedInBrowser&&this.browserFrameTracking){const r=this.pageFrames.get(e.frame);return void(r&&(r.deletedTime=t.startTime))}if(t.name===p.DevToolsMetadataEvent.AuctionWorkletRunningInProcess&&this.browserFrameTracking){const r=new y(t,e);this.auctionWorklets.set(e.target,r)}if(t.name===p.DevToolsMetadataEvent.AuctionWorkletDoneWithProcess&&this.browserFrameTracking){const r=this.auctionWorklets.get(e.target);r&&(r.endTime=t.startTime)}}}else{const e=t.args?.data?.requestId;"string"==typeof e&&this.requestsFromBrowser.set(e,t)}}ensureNamedTrack(e){let t=this.namedTracks.get(e);return t||(t=new v,t.type=e,this.tracksInternal.push(t),this.namedTracks.set(e,t),t)}findAncestorEvent(e){for(let t=this.eventStack.length-1;t>=0;--t){const r=this.eventStack[t];if(r.name===e)return r}return null}addPageFrame(e,t){const r=t.parent&&this.pageFrames.get(t.parent);if(t.parent&&!r)return!1;const a=new f(t);return this.pageFrames.set(a.frameId,a),a.update(e.startTime,t),r&&r.addChild(a),!0}reset(){this.isGenericTraceInternal=!1,this.tracksInternal=[],this.namedTracks=new Map,this.inspectedTargetEventsInternal=[],this.timeMarkerEventsInternal=[],this.sessionId=null,this.mainFrameNodeId=null,this.cpuProfilesInternal=[],this.workerIdByThread=new WeakMap,this.pageFrames=new Map,this.auctionWorklets=new Map,this.requestsFromBrowser=new Map,this.minimumRecordTimeInternal=0,this.maximumRecordTimeInternal=0,this.totalBlockingTimeInternal=-1,this.estimatedTotalBlockingTime=0}isGenericTrace(){return this.isGenericTraceInternal}tracingModel(){return this.tracingModelInternal}minimumRecordTime(){return this.minimumRecordTimeInternal}maximumRecordTime(){return this.maximumRecordTimeInternal}inspectedTargetEvents(){return this.inspectedTargetEventsInternal}tracks(){return this.tracksInternal}isEmpty(){return 0===this.minimumRecordTime()&&0===this.maximumRecordTime()}timeMarkerEvents(){return this.timeMarkerEventsInternal}rootFrames(){return Array.from(this.pageFrames.values()).filter((e=>!e.parent))}pageURL(){return this.mainFrame&&this.mainFrame.url||a.DevToolsPath.EmptyUrlString}pageFrameById(e){return e&&this.pageFrames.get(e)||null}networkRequests(){if(this.isGenericTrace())return[];const e=new Map,t=[],r=[],a=new Set([g.ResourceWillSendRequest,g.ResourceSendRequest,g.ResourceReceiveResponse,g.ResourceReceivedData,g.ResourceFinish,g.ResourceMarkAsCached]),n=this.inspectedTargetEvents();for(let e=0;e<n.length;++e){const t=n[e];if(!a.has(t.name))continue;const r=p.globalEventId(t,"requestId"),s=t.args?.data?.requestId;if(t.name===g.ResourceSendRequest&&s&&this.requestsFromBrowser.has(s)){const e=this.requestsFromBrowser.get(s);e&&i(e,r)}i(t,r)}function i(a,n){let i=e.get(n);i?i.addEvent(a):(i=new I(a),e.set(n,i),i.startTime?t.push(i):r.push(i))}return r.concat(t)}}var g,T;!function(e){e.Task="RunTask",e.Program="Program",e.EventDispatch="EventDispatch",e.GPUTask="GPUTask",e.Animation="Animation",e.RequestMainThreadFrame="RequestMainThreadFrame",e.BeginFrame="BeginFrame",e.NeedsBeginFrameChanged="NeedsBeginFrameChanged",e.BeginMainThreadFrame="BeginMainThreadFrame",e.ActivateLayerTree="ActivateLayerTree",e.DrawFrame="DrawFrame",e.DroppedFrame="DroppedFrame",e.HitTest="HitTest",e.ScheduleStyleRecalculation="ScheduleStyleRecalculation",e.RecalculateStyles="RecalculateStyles",e.UpdateLayoutTree="UpdateLayoutTree",e.InvalidateLayout="InvalidateLayout",e.Layerize="Layerize",e.Layout="Layout",e.LayoutShift="LayoutShift",e.UpdateLayer="UpdateLayer",e.UpdateLayerTree="UpdateLayerTree",e.PaintSetup="PaintSetup",e.Paint="Paint",e.PaintImage="PaintImage",e.PrePaint="PrePaint",e.Rasterize="Rasterize",e.RasterTask="RasterTask",e.ScrollLayer="ScrollLayer",e.Commit="Commit",e.CompositeLayers="CompositeLayers",e.ComputeIntersections="IntersectionObserverController::computeIntersections",e.InteractiveTime="InteractiveTime",e.ScheduleStyleInvalidationTracking="ScheduleStyleInvalidationTracking",e.StyleRecalcInvalidationTracking="StyleRecalcInvalidationTracking",e.StyleInvalidatorInvalidationTracking="StyleInvalidatorInvalidationTracking",e.LayoutInvalidationTracking="LayoutInvalidationTracking",e.ParseHTML="ParseHTML",e.ParseAuthorStyleSheet="ParseAuthorStyleSheet",e.TimerInstall="TimerInstall",e.TimerRemove="TimerRemove",e.TimerFire="TimerFire",e.XHRReadyStateChange="XHRReadyStateChange",e.XHRLoad="XHRLoad",e.CompileScript="v8.compile",e.CompileCode="V8.CompileCode",e.OptimizeCode="V8.OptimizeCode",e.EvaluateScript="EvaluateScript",e.CacheScript="v8.produceCache",e.CompileModule="v8.compileModule",e.EvaluateModule="v8.evaluateModule",e.CacheModule="v8.produceModuleCache",e.WasmStreamFromResponseCallback="v8.wasm.streamFromResponseCallback",e.WasmCompiledModule="v8.wasm.compiledModule",e.WasmCachedModule="v8.wasm.cachedModule",e.WasmModuleCacheHit="v8.wasm.moduleCacheHit",e.WasmModuleCacheInvalid="v8.wasm.moduleCacheInvalid",e.FrameStartedLoading="FrameStartedLoading",e.CommitLoad="CommitLoad",e.MarkLoad="MarkLoad",e.MarkDOMContent="MarkDOMContent",e.MarkFirstPaint="firstPaint",e.MarkFCP="firstContentfulPaint",e.MarkLCPCandidate="largestContentfulPaint::Candidate",e.MarkLCPInvalidate="largestContentfulPaint::Invalidate",e.NavigationStart="navigationStart",e.TimeStamp="TimeStamp",e.ConsoleTime="ConsoleTime",e.UserTiming="UserTiming",e.EventTiming="EventTiming",e.ResourceWillSendRequest="ResourceWillSendRequest",e.ResourceSendRequest="ResourceSendRequest",e.ResourceReceiveResponse="ResourceReceiveResponse",e.ResourceReceivedData="ResourceReceivedData",e.ResourceFinish="ResourceFinish",e.ResourceMarkAsCached="ResourceMarkAsCached",e.RunMicrotasks="RunMicrotasks",e.FunctionCall="FunctionCall",e.GCEvent="GCEvent",e.MajorGC="MajorGC",e.MinorGC="MinorGC",e.JSFrame="JSFrame",e.JSSample="JSSample",e.JSIdleFrame="JSIdleFrame",e.JSIdleSample="JSIdleSample",e.JSSystemFrame="JSSystemFrame",e.JSSystemSample="JSSystemSample",e.JSRoot="JSRoot",e.V8Sample="V8Sample",e.JitCodeAdded="JitCodeAdded",e.JitCodeMoved="JitCodeMoved",e.StreamingCompileScript="v8.parseOnBackground",e.StreamingCompileScriptWaiting="v8.parseOnBackgroundWaiting",e.StreamingCompileScriptParsing="v8.parseOnBackgroundParsing",e.BackgroundDeserialize="v8.deserializeOnBackground",e.FinalizeDeserialization="V8.FinalizeDeserialization",e.V8Execute="V8.Execute",e.UpdateCounters="UpdateCounters",e.RequestAnimationFrame="RequestAnimationFrame",e.CancelAnimationFrame="CancelAnimationFrame",e.FireAnimationFrame="FireAnimationFrame",e.RequestIdleCallback="RequestIdleCallback",e.CancelIdleCallback="CancelIdleCallback",e.FireIdleCallback="FireIdleCallback",e.WebSocketCreate="WebSocketCreate",e.WebSocketSendHandshakeRequest="WebSocketSendHandshakeRequest",e.WebSocketReceiveHandshakeResponse="WebSocketReceiveHandshakeResponse",e.WebSocketDestroy="WebSocketDestroy",e.EmbedderCallback="EmbedderCallback",e.SetLayerTreeId="SetLayerTreeId",e.TracingStartedInPage="TracingStartedInPage",e.TracingSessionIdForWorker="TracingSessionIdForWorker",e.StartProfiling="CpuProfiler::StartProfiling",e.DecodeImage="Decode Image",e.ResizeImage="Resize Image",e.DrawLazyPixelRef="Draw LazyPixelRef",e.DecodeLazyPixelRef="Decode LazyPixelRef",e.LazyPixelRef="LazyPixelRef",e.LayerTreeHostImplSnapshot="cc::LayerTreeHostImpl",e.PictureSnapshot="cc::Picture",e.DisplayItemListSnapshot="cc::DisplayItemList",e.InputLatencyMouseMove="InputLatency::MouseMove",e.InputLatencyMouseWheel="InputLatency::MouseWheel",e.ImplSideFling="InputHandlerProxy::HandleGestureFling::started",e.GCCollectGarbage="BlinkGC.AtomicPhase",e.CryptoDoEncrypt="DoEncrypt",e.CryptoDoEncryptReply="DoEncryptReply",e.CryptoDoDecrypt="DoDecrypt",e.CryptoDoDecryptReply="DoDecryptReply",e.CryptoDoDigest="DoDigest",e.CryptoDoDigestReply="DoDigestReply",e.CryptoDoSign="DoSign",e.CryptoDoSignReply="DoSignReply",e.CryptoDoVerify="DoVerify",e.CryptoDoVerifyReply="DoVerifyReply",e.CpuProfile="CpuProfile",e.Profile="Profile",e.AsyncTask="AsyncTask"}(g||(g={})),function(e){let t;e.Category={Console:"blink.console",UserTiming:"blink.user_timing",Loading:"loading"},function(e){e.LongTask="LongTask",e.ForcedStyle="ForcedStyle",e.ForcedLayout="ForcedLayout",e.IdleDeadlineExceeded="IdleDeadlineExceeded",e.LongHandler="LongHandler",e.LongRecurringHandler="LongRecurringHandler",e.V8Deopt="V8Deopt",e.LongInteraction="LongInteraction"}(t=e.WarningType||(e.WarningType={})),e.WorkerThreadName="DedicatedWorker thread",e.WorkerThreadNameLegacy="DedicatedWorker Thread",e.RendererMainThreadName="CrRendererMain",e.BrowserMainThreadName="CrBrowserMain",e.UtilityMainThreadNameSuffix="CrUtilityMain",e.AuctionWorkletThreadName="AuctionV8HelperThread",e.DevToolsMetadataEvent={TracingStartedInBrowser:"TracingStartedInBrowser",TracingStartedInPage:"TracingStartedInPage",TracingSessionIdForWorker:"TracingSessionIdForWorker",FrameCommittedInBrowser:"FrameCommittedInBrowser",ProcessReadyInBrowser:"ProcessReadyInBrowser",FrameDeletedInBrowser:"FrameDeletedInBrowser",AuctionWorkletRunningInProcess:"AuctionWorkletRunningInProcess",AuctionWorkletDoneWithProcess:"AuctionWorkletDoneWithProcess"},e.Thresholds={LongTask:50,Handler:150,RecurringHandler:50,ForcedLayout:30,IdleCallbackAddon:5}}(p||(p={}));class v{name;type;forMainFrame;url;events;asyncEvents;tasks;eventsForTreeViewInternal;thread;constructor(){this.name="",this.type=T.Other,this.forMainFrame=!1,this.url=a.DevToolsPath.EmptyUrlString,this.events=[],this.asyncEvents=[],this.tasks=[],this.eventsForTreeViewInternal=null,this.thread=null}eventsForTreeView(){if(this.eventsForTreeViewInternal)return this.eventsForTreeViewInternal;const t=[];function r(){const e=t[t.length-1];if(void 0!==e){const t=e.endTime;if(void 0!==t)return t}throw new Error("End time does not exist on event.")}this.eventsForTreeViewInternal=[...this.events];for(const a of this.asyncEvents){const n=a.startTime;let i=a.endTime;for(void 0===i&&(i=n);t.length&&n>=r();)t.pop();if(t.length&&i>r()){this.eventsForTreeViewInternal=[...this.events];break}const s=new e.TracingModel.ConstructedEvent(a.categoriesString,a.name,"X",n,a.thread);s.setEndTime(i),s.addArgs(a.args),this.eventsForTreeViewInternal.push(s),t.push(s)}return this.eventsForTreeViewInternal}}!function(e){e.MainThread="MainThread",e.Worker="Worker",e.Animation="Animation",e.Raster="Raster",e.Experience="Experience",e.Other="Other"}(T||(T={}));class f{frameId;url;name;children;parent;processes;deletedTime;ownerNode;constructor(e){this.frameId=e.frame,this.url=e.url||a.DevToolsPath.EmptyUrlString,this.name=e.name,this.children=[],this.parent=null,this.processes=[],this.deletedTime=null,this.ownerNode=null}update(e,t){this.url=t.url||"",this.name=t.name,t.processId?this.processes.push({time:e,processId:t.processId,processPseudoId:"",url:t.url||""}):this.processes.push({time:e,processId:-1,processPseudoId:t.processPseudoId,url:t.url||""})}processReady(e,t){for(const r of this.processes)r.processPseudoId===e&&(r.processPseudoId="",r.processId=t)}addChild(e){this.children.push(e),e.parent=this}}class y{targetId;processId;host;startTime;endTime;workletType;constructor(e,t){this.targetId="string"==typeof t.target?t.target:"",this.processId="number"==typeof t.pid?t.pid:0,this.host="string"==typeof t.host?t.host:void 0,this.startTime=e.startTime,this.endTime=1/0,"bidder"===t.type?this.workletType=1:"seller"===t.type?this.workletType=2:this.workletType=3}}class I{startTime;endTime;encodedDataLength;decodedBodyLength;children;timing;mimeType;url;requestMethod;transferSize;maybeDiskCached;memoryCachedInternal;priority;finishTime;responseTime;fromServiceWorker;hasCachedResource;constructor(e){const t=e.name===g.ResourceSendRequest||e.name===g.ResourceWillSendRequest;this.startTime=t?e.startTime:0,this.endTime=1/0,this.encodedDataLength=0,this.decodedBodyLength=0,this.children=[],this.transferSize=0,this.maybeDiskCached=!1,this.memoryCachedInternal=!1,this.addEvent(e)}addEvent(e){this.children.push(e),this.startTime=Math.min(this.startTime,e.startTime);const t=e.args.data;t.mimeType&&(this.mimeType=t.mimeType),"priority"in t&&(this.priority=t.priority),e.name===g.ResourceFinish&&(this.endTime=e.startTime),t.finishTime&&(this.finishTime=1e3*t.finishTime),this.responseTime||e.name!==g.ResourceReceiveResponse&&e.name!==g.ResourceReceivedData||(this.responseTime=e.startTime);const r=t.encodedDataLength||0;e.name===g.ResourceMarkAsCached&&(this.memoryCachedInternal=!0),e.name===g.ResourceReceiveResponse&&(t.fromCache&&(this.maybeDiskCached=!0),t.fromServiceWorker&&(this.fromServiceWorker=!0),t.hasCachedResource&&(this.hasCachedResource=!0),this.encodedDataLength=r),e.name===g.ResourceReceivedData&&(this.encodedDataLength+=r),e.name===g.ResourceFinish&&r&&(this.encodedDataLength=r,this.transferSize=r);const a=t.decodedBodyLength;e.name===g.ResourceFinish&&a&&(this.decodedBodyLength=a),this.url||(this.url=t.url),this.requestMethod||(this.requestMethod=t.requestMethod),this.timing||(this.timing=t.timing),t.fromServiceWorker&&(this.fromServiceWorker=!0)}cached(){return Boolean(this.memoryCachedInternal)||Boolean(this.maybeDiskCached)&&!this.transferSize&&!this.fromServiceWorker}memoryCached(){return this.memoryCachedInternal}getSendReceiveTiming(){if(this.cached()||!this.timing)return{sendStartTime:this.startTime,headersEndTime:this.startTime};const e=1e3*this.timing.requestTime;return{sendStartTime:e+this.timing.sendStart,headersEndTime:e+this.timing.receiveHeadersEnd}}getStartTime(){return Math.min(this.startTime,!this.cached()&&this.timing&&1e3*this.timing.requestTime||1/0)}beginTime(){return Math.min(this.getStartTime(),!this.cached()&&this.timing&&1e3*this.timing.pushStart||1/0)}}class S{type;startTime;tracingEvent;frame;nodeId;nodeName;invalidationSet;invalidatedSelectorId;changedId;changedClass;changedAttribute;changedPseudo;selectorPart;extraData;invalidationList;cause;linkedRecalcStyleEvent;linkedLayoutEvent;constructor(e,t){this.type=e.name,this.startTime=e.startTime,this.tracingEvent=e;const r=e.args.data;this.frame=r.frame,this.nodeId=r.nodeId,this.nodeName=r.nodeName,this.invalidationSet=r.invalidationSet,this.invalidatedSelectorId=r.invalidatedSelectorId,this.changedId=r.changedId,this.changedClass=r.changedClass,this.changedAttribute=r.changedAttribute,this.changedPseudo=r.changedPseudo,this.selectorPart=r.selectorPart,this.extraData=r.extraData,this.invalidationList=r.invalidationList,this.cause={reason:r.reason,stackTrace:t.stackTrace},this.linkedRecalcStyleEvent=!1,this.linkedLayoutEvent=!1,!this.cause.reason&&this.cause.stackTrace&&this.type===g.LayoutInvalidationTracking&&(this.cause.reason="Layout forced")}}class k{lastRecalcStyle;didPaint;invalidations;invalidationsByNodeId;constructor(){this.lastRecalcStyle=null,this.didPaint=!1,this.initializePerFrameState(),this.invalidations={},this.invalidationsByNodeId={}}static invalidationEventsFor(e){return P.get(e)||null}addInvalidation(e){if(this.startNewFrameIfNeeded(),!e.nodeId)return console.error("Invalidation lacks node information."),void console.error(e);if(e.type===g.StyleRecalcInvalidationTracking&&"StyleInvalidator"===e.cause.reason)return;if(e.type===g.ScheduleStyleInvalidationTracking||e.type===g.StyleInvalidatorInvalidationTracking||e.type===g.StyleRecalcInvalidationTracking){e.startTime&&this.lastRecalcStyle&&void 0!==this.lastRecalcStyle.endTime&&e.startTime>=this.lastRecalcStyle.startTime&&e.startTime<=this.lastRecalcStyle.endTime&&this.associateWithLastRecalcStyleEvent(e)}this.invalidations[e.type]?this.invalidations[e.type].push(e):this.invalidations[e.type]=[e],e.nodeId&&(this.invalidationsByNodeId[e.nodeId]?this.invalidationsByNodeId[e.nodeId].push(e):this.invalidationsByNodeId[e.nodeId]=[e])}didRecalcStyle(e){this.lastRecalcStyle=e;const t=[g.ScheduleStyleInvalidationTracking,g.StyleInvalidatorInvalidationTracking,g.StyleRecalcInvalidationTracking];for(const e of this.invalidationsOfTypes(t))this.associateWithLastRecalcStyleEvent(e)}associateWithLastRecalcStyleEvent(e){if(e.linkedRecalcStyleEvent)return;if(!this.lastRecalcStyle)throw new Error("Last recalculate style event not set.");const t=this.lastRecalcStyle.args.beginData.frame;e.type===g.StyleInvalidatorInvalidationTracking?this.addSyntheticStyleRecalcInvalidations(this.lastRecalcStyle,t,e):e.type===g.ScheduleStyleInvalidationTracking||this.addInvalidationToEvent(this.lastRecalcStyle,t,e),e.linkedRecalcStyleEvent=!0}addSyntheticStyleRecalcInvalidations(e,t,r){if(r.invalidationList){if(!r.nodeId)return console.error("Invalidation lacks node information."),void console.error(r);for(let e=0;e<r.invalidationList.length;e++){const a=r.invalidationList[e].id;let n;const i=this.invalidationsByNodeId[r.nodeId]||[];for(let e=0;e<i.length;e++){const r=i[e];r.frame===t&&r.invalidationSet===a&&r.type===g.ScheduleStyleInvalidationTracking&&(n=r)}n&&this.addSyntheticStyleRecalcInvalidation(n.tracingEvent,r)}}else this.addSyntheticStyleRecalcInvalidation(r.tracingEvent,r)}addSyntheticStyleRecalcInvalidation(e,t){const r=R.forEvent(e),a=new S(e,r);a.type=g.StyleRecalcInvalidationTracking,t.cause.reason&&(a.cause.reason=t.cause.reason),t.selectorPart&&(a.selectorPart=t.selectorPart),a.linkedRecalcStyleEvent||this.associateWithLastRecalcStyleEvent(a)}didLayout(e){const t=e.args.beginData.frame;for(const r of this.invalidationsOfTypes([g.LayoutInvalidationTracking]))r.linkedLayoutEvent||(this.addInvalidationToEvent(e,t,r),r.linkedLayoutEvent=!0)}addInvalidationToEvent(e,t,r){if(t!==r.frame)return;const a=P.get(e);a?a.push(r):P.set(e,[r])}invalidationsOfTypes(e){const t=this.invalidations;return e||(e=Object.keys(t)),function*(){if(e)for(let r=0;r<e.length;++r){const a=t[e[r]]||[];for(let e=0;e<a.length;++e)yield a[e]}}()}startNewFrameIfNeeded(){this.didPaint&&this.initializePerFrameState()}initializePerFrameState(){this.invalidations={},this.invalidationsByNodeId={},this.lastRecalcStyle=null,this.didPaint=!1}}class F{initiatorByType;constructor(){if(F.initialize(),this.initiatorByType=new Map,F.asyncEvents)for(const e of F.asyncEvents.keys())this.initiatorByType.set(e,new Map)}static initialize(){if(F.asyncEvents)return;const e=new Map;e.set(g.TimerInstall,{causes:[g.TimerFire],joinBy:"timerId"}),e.set(g.ResourceSendRequest,{causes:[g.ResourceMarkAsCached,g.ResourceReceiveResponse,g.ResourceReceivedData,g.ResourceFinish],joinBy:"requestId"}),e.set(g.RequestAnimationFrame,{causes:[g.FireAnimationFrame],joinBy:"id"}),e.set(g.RequestIdleCallback,{causes:[g.FireIdleCallback],joinBy:"id"}),e.set(g.WebSocketCreate,{causes:[g.WebSocketSendHandshakeRequest,g.WebSocketReceiveHandshakeResponse,g.WebSocketDestroy],joinBy:"identifier"}),F.asyncEvents=e,F.typeToInitiator=new Map;for(const t of e){const e=t[1].causes;for(const r of e)F.typeToInitiator.set(r,t[0])}}processEvent(e){if(!F.typeToInitiator||!F.asyncEvents)return;let t=F.typeToInitiator.get(e.name);const r=!t;t||(t=e.name);const a=F.asyncEvents.get(t);if(!a)return;const n=p.globalEventId(e,a.joinBy);if(!n)return;const i=this.initiatorByType.get(t);if(i){if(r)return void i.set(n,e);const t=i.get(n),a=R.forEvent(e);a.setInitiator(t||null),!a.frameId&&t&&(a.frameId=p.eventFrameId(t))}}static asyncEvents=null;static typeToInitiator=null}class R{warning;previewElement;url;backendNodeIds;stackTrace;picture;initiatorInternal;frameId;timeWaitingForMainThread;constructor(){this.warning=null,this.previewElement=null,this.url=null,this.backendNodeIds=[],this.stackTrace=null,this.picture=null,this.initiatorInternal=null,this.frameId=null}setInitiator(e){if(this.initiatorInternal=e,!e||this.url)return;const t=R.forEvent(e).url;t&&(this.url=t)}initiator(){return this.initiatorInternal}topFrame(){const e=this.stackTraceForSelfOrInitiator();return e&&e[0]||null}stackTraceForSelfOrInitiator(){return this.stackTrace||this.initiatorInternal&&R.forEvent(this.initiatorInternal).stackTrace}static forEvent(t){return t instanceof e.TracingModel.PayloadEvent?R.forTraceEventData(t.rawPayload()):t instanceof e.TracingModel.Event?C(t):R.forTraceEventData(t)}static forTraceEventData(e){return C(e)}}function C(e){let t=E.get(e);return t||(t=new R,E.set(e,t)),t}const E=new WeakMap,P=new WeakMap;var M=Object.freeze({__proto__:null,get TimelineModelImpl(){return p},get RecordType(){return g},Track:v,get TrackType(){return T},PageFrame:f,AuctionWorklet:y,NetworkRequest:I,InvalidationTrackingEvent:S,InvalidationTracker:k,TimelineAsyncEventTracker:F,EventOnTimelineData:R});class w{}class L extends w{visibleTypes;constructor(e){super(),this.visibleTypes=new Set(e)}accept(e){return this.visibleTypes.has(L.eventType(e))}static eventType(t){return e.TracingModel.eventHasCategory(t,p.Category.Console)?g.ConsoleTime:e.TracingModel.eventHasCategory(t,p.Category.UserTiming)?g.UserTiming:t.name}}var b=Object.freeze({__proto__:null,TimelineModelFilter:w,TimelineVisibleEventsFilter:L,TimelineInvisibleEventsFilter:class extends w{invisibleTypes;constructor(e){super(),this.invisibleTypes=new Set(e)}accept(e){return!this.invisibleTypes.has(L.eventType(e))}},ExclusiveNameFilter:class extends w{excludeNames;constructor(e){super(),this.excludeNames=new Set(e)}accept(e){return!this.excludeNames.has(e.name)}}});class D extends e.LayerTreeBase.LayerTreeBase{tileById;paintProfilerModel;constructor(t){super(t),this.tileById=new Map,this.paintProfilerModel=t&&t.model(e.PaintProfiler.PaintProfilerModel)}async setLayers(e,t,r){const a=new Set;if(e)this.extractNodeIdsToResolve(a,{},e);else if(t)for(let e=0;e<t.length;++e)this.extractNodeIdsToResolve(a,{},t[e]);await this.resolveBackendNodeIds(a);const n=this.layersById;if(this.layersById=new Map,this.setContentRoot(null),e){const t=this.innerSetLayers(n,e);this.setRoot(t)}else if(t){const e=t.map(this.innerSetLayers.bind(this,n)),r=this.contentRoot();if(!r)throw new Error("Content root is not set.");this.setRoot(r);for(let t=0;t<e.length;++t)e[t].id()!==r.id()&&r.addChild(e[t])}this.setPaints(r)}setTiles(e){this.tileById=new Map;for(const t of e)this.tileById.set(t.id,t)}pictureForRasterTile(e){const r=this.tileById.get("cc::Tile/"+e);if(!r)return t.Console.Console.instance().error(`Tile ${e} is missing`),Promise.resolve(null);const a=this.layerById(r.layer_id);return a?a.pictureForRect(r.content_rect):(t.Console.Console.instance().error(`Layer ${r.layer_id} for tile ${e} is not found`),Promise.resolve(null))}setPaints(e){for(let t=0;t<e.length;++t){const r=this.layersById.get(e[t].layerId());r&&r.addPaintEvent(e[t])}}innerSetLayers(e,t){let r=e.get(t.layer_id);r?r.reset(t):r=new B(this.paintProfilerModel,t),this.layersById.set(t.layer_id,r),t.owner_node&&r.setNode(this.backendNodeIdToNode().get(t.owner_node)||null),!this.contentRoot()&&r.drawsContent()&&this.setContentRoot(r);for(let a=0;t.children&&a<t.children.length;++a)r.addChild(this.innerSetLayers(e,t.children[a]));return r}extractNodeIdsToResolve(e,t,r){const a=r.owner_node;a&&!this.backendNodeIdToNode().has(a)&&e.add(a);for(let a=0;r.children&&a<r.children.length;++a)this.extractNodeIdsToResolve(e,t,r.children[a])}}class B{parentLayerId;parentInternal;layerId;nodeInternal;offsetXInternal;offsetYInternal;widthInternal;heightInternal;childrenInternal;quadInternal;scrollRectsInternal;gpuMemoryUsageInternal;paints;compositingReasons;compositingReasonIds;drawsContentInternal;paintProfilerModel;constructor(e,t){this.parentLayerId=null,this.parentInternal=null,this.layerId="",this.nodeInternal=null,this.offsetXInternal=-1,this.offsetYInternal=-1,this.widthInternal=-1,this.heightInternal=-1,this.childrenInternal=[],this.quadInternal=[],this.scrollRectsInternal=[],this.gpuMemoryUsageInternal=-1,this.paints=[],this.compositingReasons=[],this.compositingReasonIds=[],this.drawsContentInternal=!1,this.paintProfilerModel=e,this.reset(t)}reset(e){this.nodeInternal=null,this.layerId=String(e.layer_id),this.offsetXInternal=e.position[0],this.offsetYInternal=e.position[1],this.widthInternal=e.bounds.width,this.heightInternal=e.bounds.height,this.childrenInternal=[],this.parentLayerId=null,this.parentInternal=null,this.quadInternal=e.layer_quad||[],this.createScrollRects(e),this.compositingReasons=e.compositing_reasons||[],this.compositingReasonIds=e.compositing_reason_ids||[],this.drawsContentInternal=Boolean(e.draws_content),this.gpuMemoryUsageInternal=e.gpu_memory_usage,this.paints=[]}id(){return this.layerId}parentId(){return this.parentLayerId}parent(){return this.parentInternal}isRoot(){return!this.parentId()}children(){return this.childrenInternal}addChild(e){const t=e;t.parentInternal&&console.assert(!1,"Child already has a parent"),this.childrenInternal.push(t),t.parentInternal=this,t.parentLayerId=this.layerId}setNode(e){this.nodeInternal=e}node(){return this.nodeInternal}nodeForSelfOrAncestor(){let e=this;for(;e;e=e.parent())if(e.node())return e.node();return null}offsetX(){return this.offsetXInternal}offsetY(){return this.offsetYInternal}width(){return this.widthInternal}height(){return this.heightInternal}transform(){return null}quad(){return this.quadInternal}anchorPoint(){return[.5,.5,0]}invisible(){return!1}paintCount(){return 0}lastPaintRect(){return null}scrollRects(){return this.scrollRectsInternal}stickyPositionConstraint(){return null}gpuMemoryUsage(){return this.gpuMemoryUsageInternal}snapshots(){return this.paints.map((e=>e.snapshotPromise().then((e=>{if(!e)return null;return{rect:{x:e.rect[0],y:e.rect[1],width:e.rect[2],height:e.rect[3]},snapshot:e.snapshot}}))))}pictureForRect(e){return Promise.all(this.paints.map((e=>e.picturePromise()))).then((r=>{const a=r.filter((r=>{return r&&(a=r.rect,n=e,t(a[0],a[0]+a[2],n[0],n[0]+n[2])&&t(a[1],a[1]+a[3],n[1],n[1]+n[3]));var a,n})).map((e=>({x:e.rect[0],y:e.rect[1],picture:e.serializedPicture})));if(!a.length||!this.paintProfilerModel)return null;const n=a.reduce(((e,t)=>Math.min(e,t.x)),1/0),i=a.reduce(((e,t)=>Math.min(e,t.y)),1/0),s={x:e[0]-n,y:e[1]-i,width:e[2],height:e[3]};return this.paintProfilerModel.loadSnapshotFromFragments(a).then((e=>e?{rect:s,snapshot:e}:null))}));function t(e,t,r,a){return console.assert(e<=t&&r<=a,"segments should be specified as ordered pairs"),t>r&&e<a}}scrollRectsFromParams(e,t){return{rect:{x:e[0],y:e[1],width:e[2],height:e[3]},type:t}}createScrollRects(e){const t=[];e.non_fast_scrollable_region&&t.push(this.scrollRectsFromParams(e.non_fast_scrollable_region,"NonFastScrollable")),e.touch_event_handler_region&&t.push(this.scrollRectsFromParams(e.touch_event_handler_region,"TouchEventHandler")),e.wheel_event_handler_region&&t.push(this.scrollRectsFromParams(e.wheel_event_handler_region,"WheelEventHandler")),e.scroll_event_handler_region&&t.push(this.scrollRectsFromParams(e.scroll_event_handler_region,"RepaintsOnScroll")),this.scrollRectsInternal=t}addPaintEvent(e){this.paints.push(e)}requestCompositingReasons(){return Promise.resolve(this.compositingReasons)}requestCompositingReasonIds(){return Promise.resolve(this.compositingReasonIds)}drawsContent(){return this.drawsContentInternal}}var N=Object.freeze({__proto__:null,TracingLayerTree:D,TracingLayer:B});class W{categoryMapper;frames;frameById;beginFrameQueue;minimumRecordTime;lastFrame;mainFrameCommitted;mainFrameRequested;lastLayerTree;framePendingActivation;currentTaskTimeByCategory;target;framePendingCommit;lastBeginFrame;lastDroppedFrame;lastNeedsBeginFrame;lastTaskBeginTime;layerTreeId;currentProcessMainThread;constructor(e){this.categoryMapper=e,this.reset()}getFrames(){return this.frames}getFramesWithinWindow(e,t){const r=a.ArrayUtilities.lowerBound(this.frames,e||0,((e,t)=>e-t.endTime)),n=a.ArrayUtilities.lowerBound(this.frames,t||1/0,((e,t)=>e-t.startTime));return this.frames.slice(r,n)}hasRasterTile(e){const t=e.args.tileData;if(!t)return!1;const r=t.sourceFrameNumber,a=r&&this.frameById[r];return!(!a||!a.layerTree)}rasterTilePromise(e){if(!this.target)return Promise.resolve(null);const t=e.args.tileData,r=t.sourceFrameNumber,a=t.tileId&&t.tileId.id_ref,n=r&&this.frameById[r];return n&&n.layerTree&&a?n.layerTree.layerTreePromise().then((e=>e&&e.pictureForRasterTile(a))):Promise.resolve(null)}reset(){this.minimumRecordTime=1/0,this.frames=[],this.frameById={},this.beginFrameQueue=new U,this.lastFrame=null,this.lastLayerTree=null,this.mainFrameCommitted=!1,this.mainFrameRequested=!1,this.framePendingCommit=null,this.lastBeginFrame=null,this.lastDroppedFrame=null,this.lastNeedsBeginFrame=null,this.framePendingActivation=null,this.lastTaskBeginTime=null,this.target=null,this.layerTreeId=null,this.currentTaskTimeByCategory={}}handleBeginFrame(e,t){this.lastFrame||this.startFrame(e),this.lastBeginFrame=e,this.beginFrameQueue.addFrameIfNotExists(t,e,!1,!1)}handleDroppedFrame(e,t,r){this.lastFrame||this.startFrame(e),this.beginFrameQueue.addFrameIfNotExists(t,e,!0,r),this.beginFrameQueue.setDropped(t,!0),this.beginFrameQueue.setPartial(t,r)}handleDrawFrame(e,t){if(this.lastFrame){if(this.mainFrameCommitted||!this.mainFrameRequested){if(this.lastNeedsBeginFrame){(this.framePendingActivation?this.framePendingActivation.triggerTime:this.lastBeginFrame||this.lastNeedsBeginFrame)>this.lastFrame.startTime&&(this.lastFrame.idle=!0,this.lastBeginFrame=null),this.lastNeedsBeginFrame=null}const e=this.beginFrameQueue.processPendingBeginFramesOnDrawFrame(t);for(const t of e){const e=this.lastFrame.idle;this.startFrame(t.startTime),e&&this.framePendingActivation&&this.commitPendingFrame(),t.isDropped&&(this.lastFrame.dropped=!0),t.isPartial&&(this.lastFrame.isPartial=!0)}}this.mainFrameCommitted=!1}else this.startFrame(e)}handleActivateLayerTree(){this.lastFrame&&this.framePendingActivation&&!this.lastNeedsBeginFrame&&this.commitPendingFrame()}handleRequestMainThreadFrame(){this.lastFrame&&(this.mainFrameRequested=!0)}handleCommit(){this.framePendingCommit&&(this.framePendingActivation=this.framePendingCommit,this.framePendingCommit=null,this.mainFrameRequested=!1,this.mainFrameCommitted=!0)}handleLayerTreeSnapshot(e){this.lastLayerTree=e}handleNeedFrameChanged(e,t){t&&(this.lastNeedsBeginFrame=e)}startFrame(e){this.lastFrame&&this.flushFrame(this.lastFrame,e),this.lastFrame=new x(e,e-this.minimumRecordTime)}flushFrame(e,t){e.setLayerTree(this.lastLayerTree),e.setEndTime(t),this.lastLayerTree&&this.lastLayerTree.setPaints(e.paints);const r=this.frames[this.frames.length-1];this.frames.length&&r&&(e.startTime!==r.endTime||e.startTime>e.endTime)&&console.assert(!1,`Inconsistent frame time for frame ${this.frames.length} (${e.startTime} - ${e.endTime})`),this.frames.push(e),"number"==typeof e.mainFrameId&&(this.frameById[e.mainFrameId]=e)}commitPendingFrame(){this.framePendingActivation&&this.lastFrame&&(this.lastFrame.addTimeForCategories(this.framePendingActivation.timeByCategory),this.lastFrame.paints=this.framePendingActivation.paints,this.lastFrame.mainFrameId=this.framePendingActivation.mainFrameId,this.framePendingActivation=null)}addTraceEvents(e,t,r){this.target=e;let a=0;this.currentProcessMainThread=r.length&&r[0].thread||null;for(let e=0;e<t.length;++e){for(;a+1<r.length&&r[a+1].time<=t[e].startTime;)this.currentProcessMainThread=r[++a].thread;this.addTraceEvent(t[e])}this.currentProcessMainThread=null}addTraceEvent(t){if(t.startTime&&t.startTime<this.minimumRecordTime&&(this.minimumRecordTime=t.startTime),t.name===g.SetLayerTreeId)this.layerTreeId=t.args.layerTreeId||t.args.data.layerTreeId;else if(t.id&&"O"===t.phase&&t.name===g.LayerTreeHostImplSnapshot&&Number(t.id)===this.layerTreeId&&this.target){const e=t;this.handleLayerTreeSnapshot(new A(this.target,e))}else this.processCompositorEvents(t),t.thread===this.currentProcessMainThread?this.addMainThreadTraceEvent(t):this.lastFrame&&t.selfTime&&!e.TracingModel.TracingModel.isTopLevelEvent(t)&&this.lastFrame.addTimeForCategory(this.categoryMapper(t),t.selfTime)}processCompositorEvents(e){if(e.args.layerTreeId!==this.layerTreeId)return;const t=e.startTime;e.name===g.BeginFrame?this.handleBeginFrame(t,e.args.frameSeqId):e.name===g.DrawFrame?this.handleDrawFrame(t,e.args.frameSeqId):e.name===g.ActivateLayerTree?this.handleActivateLayerTree():e.name===g.RequestMainThreadFrame?this.handleRequestMainThreadFrame():e.name===g.NeedsBeginFrameChanged?this.handleNeedFrameChanged(t,e.args.data&&e.args.data.needsBeginFrame):e.name===g.DroppedFrame&&this.handleDroppedFrame(t,e.args.frameSeqId,e.args.hasPartialUpdate)}addMainThreadTraceEvent(t){e.TracingModel.TracingModel.isTopLevelEvent(t)&&(this.currentTaskTimeByCategory={},this.lastTaskBeginTime=t.startTime),!this.framePendingCommit&&W.mainFrameMarkers.indexOf(t.name)>=0&&(this.framePendingCommit=new q(this.lastTaskBeginTime||t.startTime,this.currentTaskTimeByCategory)),this.framePendingCommit?(this.addTimeForCategory(this.framePendingCommit.timeByCategory,t),t.name===g.BeginMainThreadFrame&&t.args.data&&t.args.data.frameId&&(this.framePendingCommit.mainFrameId=t.args.data.frameId),t.name===g.Paint&&t.args.data.layerId&&R.forEvent(t).picture&&this.target&&this.framePendingCommit.paints.push(new _(t,this.target)),t.name!==g.CompositeLayers&&t.name!==g.Commit||t.args.layerTreeId!==this.layerTreeId||this.handleCommit()):this.addTimeForCategory(this.currentTaskTimeByCategory,t)}addTimeForCategory(e,t){if(!t.selfTime)return;const r=this.categoryMapper(t);e[r]=(e[r]||0)+t.selfTime}static mainFrameMarkers=[g.ScheduleStyleRecalculation,g.InvalidateLayout,g.BeginMainThreadFrame,g.ScrollLayer]}class A{target;snapshot;paintsInternal;constructor(e,t){this.target=e,this.snapshot=t}async layerTreePromise(){const e=this.snapshot.getSnapshot();if(!e)return null;const t=e.device_viewport_size,r=e.active_tiles,a=e.active_tree.root_layer,n=e.active_tree.layers,i=new D(this.target);return i.setViewportSize(t),i.setTiles(r),await i.setLayers(a,n,this.paintsInternal||[]),i}paints(){return this.paintsInternal||[]}setPaints(e){this.paintsInternal=e}}class x{startTime;startTimeOffset;endTime;duration;timeByCategory;cpuTime;idle;dropped;isPartial;layerTree;paints;mainFrameId;constructor(e,t){this.startTime=e,this.startTimeOffset=t,this.endTime=this.startTime,this.duration=0,this.timeByCategory={},this.cpuTime=0,this.idle=!1,this.dropped=!1,this.isPartial=!1,this.layerTree=null,this.paints=[],this.mainFrameId=void 0}hasWarnings(){return!1}setEndTime(e){this.endTime=e,this.duration=this.endTime-this.startTime}setLayerTree(e){this.layerTree=e}addTimeForCategories(e){for(const t in e)this.addTimeForCategory(t,e[t])}addTimeForCategory(e,t){this.timeByCategory[e]=(this.timeByCategory[e]||0)+t,this.cpuTime+=t}}class _{eventInternal;target;constructor(e,t){this.eventInternal=e,this.target=t}layerId(){return this.eventInternal.args.data.layerId}event(){return this.eventInternal}picturePromise(){const e=R.forEvent(this.eventInternal).picture;if(!e)return Promise.resolve(null);const t=e.getSnapshot(),r=t.params&&t.params.layer_rect,a=t.skp64;return Promise.resolve(r&&a?{rect:r,serializedPicture:a}:null)}async snapshotPromise(){const t=this.target&&this.target.model(e.PaintProfiler.PaintProfilerModel),r=await this.picturePromise();if(!r||!t)return null;const a=await t.loadSnapshot(r.serializedPicture);return a?{rect:r.rect,snapshot:a}:null}}class q{timeByCategory;paints;mainFrameId;triggerTime;constructor(e,t){this.timeByCategory=t,this.paints=[],this.mainFrameId=void 0,this.triggerTime=e}}class H{seqId;startTime;isDropped;isPartial;constructor(e,t,r,a){this.seqId=e,this.startTime=t,this.isDropped=r,this.isPartial=a}}class U{queueFrames;mapFrames;constructor(){this.queueFrames=[],this.mapFrames={}}addFrameIfNotExists(e,t,r,a){e in this.mapFrames||(this.mapFrames[e]=new H(e,t,r,a),this.queueFrames.push(e))}setDropped(e,t){e in this.mapFrames&&(this.mapFrames[e].isDropped=t)}setPartial(e,t){e in this.mapFrames&&(this.mapFrames[e].isPartial=t)}processPendingBeginFramesOnDrawFrame(e){const t=[];if(e in this.mapFrames){for(;this.queueFrames[0]!==e;){const e=this.queueFrames[0];this.mapFrames[e].isDropped&&t.push(this.mapFrames[e]),delete this.mapFrames[e],this.queueFrames.shift()}t.push(this.mapFrames[e]),delete this.mapFrames[e],this.queueFrames.shift()}return t}}var J=Object.freeze({__proto__:null,TimelineFrameModel:W,TracingFrameLayerTree:A,TimelineFrame:x,LayerPaintEvent:_,PendingFrame:q,TimelineFrameBeginFrameQueue:U});class z{totalTime;selfTime;id;event;parent;groupId;isGroupNodeInternal;depth;constructor(e,t){this.totalTime=0,this.selfTime=0,this.id=e,this.event=t,this.groupId="",this.isGroupNodeInternal=!1,this.depth=0}isGroupNode(){return this.isGroupNodeInternal}hasChildren(){throw"Not implemented"}setHasChildren(e){throw"Not implemented"}children(){throw"Not implemented"}searchTree(e,t){t=t||[],this.event&&e(this.event)&&t.push(this);for(const r of this.children().values())r.searchTree(e,t);return t}}class G extends z{root;hasChildrenInternal;childrenInternal;parent;constructor(e,t,r){super(e,t),this.root=r&&r.root,this.hasChildrenInternal=!1,this.childrenInternal=null,this.parent=r}hasChildren(){return this.hasChildrenInternal}setHasChildren(e){this.hasChildrenInternal=e}children(){return this.childrenInternal||this.buildChildren()}buildChildren(){const t=[];for(let e=this;e.parent&&!e.isGroupNode();e=e.parent)t.push(e);t.reverse();const r=new Map,a=this,n=this.root;if(!n)return this.childrenInternal=r,this.childrenInternal;const i=n.startTime,s=n.endTime,o=n.doNotAggregate?function(e){++c,h===t.length&&c<=t.length+2&&u(e,0);--c}:void 0,l=n.doNotAggregate?void 0:j,d=n.getEventGroupIdCallback();let c=0,h=0,m=null;function u(e,n){if(c===t.length+2){if(!m)return;return m.setHasChildren(!0),void(m.selfTime-=n)}let i,s="";l?(i=l(e),s=d?d(e):"",s&&(i+="/"+s)):i=Symbol("uniqueId");let o=r.get(i);o||(o=new G(i,e,a),o.groupId=s,r.set(i,o)),o.selfTime+=n,o.totalTime+=n,m=o}return p.forEachEvent(n.events,(function(r){const{startTime:a,endTime:n}=e.TracingModel.timesForEventInMilliseconds(r);if(++c,c>t.length+2)return;if(!function(r){const{endTime:a}=e.TracingModel.timesForEventInMilliseconds(r);if(h===t.length)return!0;if(h!==c-1)return!1;if(!a)return!1;if(!l)return r===t[h].event&&++h,!1;let n=l(r);const i=d?d(r):"";i&&(n+="/"+i);n===t[h].id&&++h;return!1}(r))return;const o=(void 0!==n?Math.min(n,s):s)-Math.max(i,a);o<0&&console.error("Negative event duration");u(r,o)}),(function(e){--c,h>c&&(h=c)}),o,i,s,n.filter,!1),this.childrenInternal=r,r}getRoot(){return this.root}}class O extends z{childrenInternal;isGroupNodeInternal;constructor(e,t,r){super(e,r),this.childrenInternal=new Map,this.parent=t,this.isGroupNodeInternal=!0}addChild(e,t,r){this.childrenInternal.set(e.id,e),this.selfTime+=t,this.totalTime+=r,e.parent=this}hasChildren(){return!0}children(){return this.childrenInternal}}class V extends z{parent;root;depth;cachedChildren;hasChildrenInternal;constructor(e,t,r,a,n){super(t,r),this.parent=n,this.root=e,this.depth=(n.depth||0)+1,this.cachedChildren=null,this.hasChildrenInternal=a}hasChildren(){return this.hasChildrenInternal}setHasChildren(e){this.hasChildrenInternal=e}children(){if(this.cachedChildren)return this.cachedChildren;const t=[0],r=[],a=[],n=new Map,i=this.root.startTime,s=this.root.endTime;let o=i;const l=this;return p.forEachEvent(this.root.events,(function(n){const{startTime:o,endTime:l}=e.TracingModel.timesForEventInMilliseconds(n),d=(void 0!==l?Math.min(l,s):s)-Math.max(o,i);d<0&&console.assert(!1,"Negative duration of an event");t[t.length-1]-=d,t.push(d);const c=j(n);r.push(c),a.push(n)}),(function(i){const{startTime:d,endTime:c}=e.TracingModel.timesForEventInMilliseconds(i),h=t.pop(),m=r.pop();let u;for(a.pop(),u=l;u.depth>1;u=u.parent)if(u.id!==r[r.length+1-u.depth])return;if(u.id!==m||r.length<l.depth)return;const p=r[r.length-l.depth];if(u=n.get(p),!u){const e=a[a.length-l.depth],t=a.length>l.depth;u=new V(l.root,p,e,t,l),n.set(p,u)}const g=void 0!==c?Math.min(c,s):s,T=g-Math.max(d,o);u.selfTime+=h||0,u.totalTime+=T,o=g}),void 0,i,s,this.root.filter,!1),this.cachedChildren=this.root.filterChildren(n),this.cachedChildren}searchTree(e,t){return t=t||[],this.event&&e(this.event)&&t.push(this),t}}function $(e){return p.isJsFrameEvent(e)?e.args.data||null:R.forEvent(e).topFrame()}function j(e){if(e.name===g.TimeStamp)return`${e.name}:${e.args.data.message}`;if(!p.isJsFrameEvent(e))return e.name;const t=e.args.data,r=t.scriptId||t.url||"",a=t.functionName;return`f:${d.isNativeRuntimeFrame(t)?d.nativeGroup(a)||a:`${a}:${t.lineNumber}:${t.columnNumber}`}@${r}`}var X=Object.freeze({__proto__:null,Node:z,TopDownNode:G,TopDownRootNode:class extends G{filter;events;startTime;endTime;eventGroupIdCallback;doNotAggregate;totalTime;selfTime;constructor(e,t,r,a,n,i){super("",null,null),this.root=this,this.events=e,this.filter=e=>t.every((t=>t.accept(e))),this.startTime=r,this.endTime=a,this.eventGroupIdCallback=i,this.doNotAggregate=n,this.totalTime=a-r,this.selfTime=this.totalTime}children(){return this.childrenInternal||this.grouppedTopNodes()}grouppedTopNodes(){const e=super.children();for(const t of e.values())this.selfTime-=t.totalTime;if(!this.eventGroupIdCallback)return e;const t=new Map;for(const r of e.values()){const e=this.eventGroupIdCallback(r.event);let a=t.get(e);a||(a=new O(e,this,r.event),t.set(e,a)),a.addChild(r,r.selfTime,r.totalTime)}return this.childrenInternal=t,t}getEventGroupIdCallback(){return this.eventGroupIdCallback}},BottomUpRootNode:class extends z{childrenInternal;events;textFilter;filter;startTime;endTime;eventGroupIdCallback;totalTime;constructor(e,t,r,a,n,i){super("",null),this.childrenInternal=null,this.events=e,this.textFilter=t,this.filter=e=>r.every((t=>t.accept(e))),this.startTime=a,this.endTime=n,this.eventGroupIdCallback=i,this.totalTime=n-a}hasChildren(){return!0}filterChildren(e){for(const[t,r]of e)r.event&&!this.textFilter.accept(r.event)&&e.delete(t);return e}children(){return this.childrenInternal||(this.childrenInternal=this.filterChildren(this.grouppedTopNodes())),this.childrenInternal}ungrouppedTopNodes(){const t=this,r=this.startTime,a=this.endTime,n=new Map,i=[a-r],s=[],o=new Map;p.forEachEvent(this.events,(function(t){const{startTime:n,endTime:l}=e.TracingModel.timesForEventInMilliseconds(t),d=(void 0!==l?Math.min(l,a):a)-Math.max(n,r);i[i.length-1]-=d,i.push(d);const c=j(t),h=!o.has(c);h&&o.set(c,d);s.push(h)}),(function(e){const r=j(e);let a=n.get(r);a||(a=new V(t,r,e,!1,t),n.set(r,a));a.selfTime+=i.pop()||0,s.pop()&&(a.totalTime+=o.get(r)||0,o.delete(r));s.length&&a.setHasChildren(!0)}),void 0,r,a,this.filter,!1),this.selfTime=i.pop()||0;for(const e of n)e[1].selfTime<=0&&n.delete(e[0]);return n}grouppedTopNodes(){const e=this.ungrouppedTopNodes();if(!this.eventGroupIdCallback)return e;const t=new Map;for(const r of e.values()){const e=this.eventGroupIdCallback(r.event);let a=t.get(e);a||(a=new O(e,this,r.event),t.set(e,a)),a.addChild(r,r.selfTime,r.selfTime)}return t}},GroupNode:O,BottomUpNode:V,eventURL:function(e){const t=e.args.data||e.args.beginData;if(t&&t.url)return t.url;let r=$(e);for(;r;){const e=r.url;if(e)return e;r=r.parent}return null},eventStackFrame:$,_eventId:j});export{J as TimelineFrameModel,c as TimelineJSProfile,M as TimelineModel,b as TimelineModelFilter,X as TimelineProfileTree,N as TracingLayerTree};
